//
//  SScooperateViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/3.
//

import UIKit

import SwiftyJSON

class SScooperateViewController: UIViewController, UITextFieldDelegate {
    
    
    var limitCountLabel: UILabel = UILabel()
    var placeholderLabel: UILabel = UILabel()
    var textView: UITextView = UITextView()
    var textField: UITextField = UITextField()
    let limitCount:Int = 200
    var cooperList = [SSCooper]()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "我的合作"
//        setuis()
        getCoopTag()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.textField.becomeFirstResponder()
        self.textView.resignFirstResponder()
    }

    func setuis() {
        
        let scrollView = UIView()
        scrollView.isUserInteractionEnabled = true
//        scrollView.backgroundColor = UIColor.random
        if IsBangs_iPhone() {
            scrollView.frame = CGRect(x: 0, y: 84, width: ScreenWidth, height: ScreenHeight - 84)
        }else{
            scrollView.frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64)
        }
        
//        scrollView.backgroundColor = UIColor.blue
        view.addSubview(scrollView)
        
        let tagTitleLab = UILabel()
        tagTitleLab.text = "请选择合作标签"
        tagTitleLab.font = UIFont.systemFont(ofSize: 16)
        tagTitleLab.frame = CGRect(x: 16, y: 10, width: 150, height: 22)
        scrollView.addSubview(tagTitleLab)
        
//        var tags = [String]()
//        tags.append("加盟/合作")
//        tags.append("全职")
//        tags.append("兼职")
//        tags.append("房产中介")
//        tags.append("有经验")
//        tags.append("有驾照")
//        for (i,title) in tags.enumerated() {
//            let cooper = SSCooper()
//            cooper.id = "\(i + 1)"
//            cooper.name = title
//            self.cooperList.append(cooper)
//        }
//
        let margin:CGFloat = 10
        var x:CGFloat = 16
        var y:CGFloat = tagTitleLab.frame.maxY + 16
        let width:CGFloat = (ScreenWidth - 16 * 2 - margin * 2)/3
        let height:CGFloat = 32
        var lastLabMaxY:CGFloat = 0
        for (i,cooper) in self.cooperList.enumerated() {
            let count = i%3
            if(count == 0&&(i != 0)){
                x = 16
                y = lastLabMaxY + 16
            }
            let btn = UIButton()
            btn.tag = i
            btn.frame = CGRect(x: x, y: y, width: width, height: height)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
//            btn.setTitle(title, for: .normal)
            btn.setTitle(cooper.name, for: .normal)
            scrollView.addSubview(btn)
            btn.layer.masksToBounds = true
            btn.layer.cornerRadius = 16
            btn.backgroundColor = UIColor.init(hex: "#E5E5E5")
            btn.setTitleColor(UIColor.black, for: .normal)
            btn.setTitleColor(UIColor.white, for: .selected)
            btn.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
//            btn.titleLabel?.textColor = UIColor.black
            
            x = btn.frame.maxX + margin
            lastLabMaxY = btn.frame.maxY
        }
        
        let instructLab = UILabel()
        instructLab.text = "自我介绍/合作内容"
        instructLab.font = UIFont.systemFont(ofSize: 16)
        instructLab.frame = CGRect(x: 16, y: lastLabMaxY + 35, width: 200, height: 22)
        scrollView.addSubview(instructLab)
        
        let textViewBG = UILabel()
        textViewBG.backgroundColor = UIColor.init(hex: "#E5E5E5")
        textViewBG.frame = CGRect(x: 16, y: instructLab.frame.maxY + 16, width: ScreenWidth - 16 * 2, height: 150)
        scrollView.addSubview(textViewBG)
        textViewBG.layer.cornerRadius = 8
        textViewBG.layer.masksToBounds = true
        textViewBG.isUserInteractionEnabled = true
        
        
        
        let textView = UITextView()
//        textView.backgroundColor = UIColor.red
        textView.backgroundColor = UIColor.clear
        textView.frame = CGRect(x: 12, y: 12, width: textViewBG.frame.width - 24, height: textViewBG.frame.height - 24)
        textView.delegate = self
        textViewBG.addSubview(textView)
        self.textView = textView
        
        let placeholderLab = UILabel()
        placeholderLab.textAlignment = .left
        placeholderLab.text = "在这里输入内容"
        placeholderLab.font = UIFont.systemFont(ofSize: 16)
        placeholderLab.frame = CGRect(x: 12, y: 12, width: 150, height: 14)
        textViewBG.addSubview(placeholderLab)
        self.placeholderLabel = placeholderLab

        let countLab = UILabel()
        countLab.text = "0/\(limitCount)"
        countLab.textAlignment = .right
        countLab.font = UIFont.systemFont(ofSize: 16)
        countLab.frame = CGRect(x: textViewBG.frame.width - 150 - 12, y: textViewBG.frame.height - 20 - 12, width: 150, height: 20)
        textViewBG.addSubview(countLab)
        self.limitCountLabel = countLab
        
        let telLab = UILabel()
        telLab.text = "联系电话："
        telLab.font = UIFont.systemFont(ofSize: 16)
        telLab.frame = CGRect(x: 16, y: textViewBG.frame.maxY + 35, width: 200, height: 22)
        scrollView.addSubview(telLab)

        let telViewBG = UILabel()
        telViewBG.backgroundColor = UIColor.init(hex: "#E5E5E5")
        telViewBG.frame = CGRect(x: 16, y: telLab.frame.maxY + 16, width: ScreenWidth - 16 * 2, height: 34)
        scrollView.addSubview(telViewBG)
        telViewBG.layer.cornerRadius = 8
        telViewBG.layer.masksToBounds = true
        telViewBG.isUserInteractionEnabled = true
        
        let telTextLab = UILabel()
        telTextLab.text = "电话*"
        telTextLab.font = UIFont.systemFont(ofSize: 14)
        telTextLab.frame = CGRect(x: 12, y: 6, width: 50, height: 22)
        telViewBG.addSubview(telTextLab)
        
        let tf = UITextField()
        tf.frame = CGRect(x: telTextLab.frame.maxX, y: 0, width: 250, height: 34)
        tf.clearButtonMode = .always
        tf.backgroundColor = .clear
        tf.keyboardType = .numberPad
        tf.returnKeyType = .done
        tf.delegate = self
        telViewBG.addSubview(tf)
//        tf.backgroundColor = UIColor.red
        self.textField = tf


        let btn = UIButton()
        btn.frame = CGRect(x: 16, y: scrollView.frame.height - 44 - 34, width: ScreenWidth - 32, height: 44)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitle("提交", for: .normal)
        scrollView.addSubview(btn)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 4
        btn.backgroundColor = UIColor.init(hex: "#E5E5E5")
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.addTarget(self, action: #selector(submitTapped(_:)), for: .touchUpInside)
//
    }
    
    @objc func btnTapped(_ button:UIButton){
        button.isSelected = !button.isSelected
        if(button.isSelected){
            button.backgroundColor = UIColor.init(hex: "#103573")
        }else{
            button.backgroundColor = UIColor.init(hex: "#E5E5E5")
        }
        let cooper:SSCooper = self.cooperList[button.tag]
        cooper.isSelected = button.isSelected
    }
    
    @objc func submitTapped(_ button:UIButton){
        var items = [SSCooper]()
        
        for cooper in self.cooperList {
            if cooper.isSelected {
                items.append(cooper)
            }
        }
        if items.count == 0{
            self.view.makeToast("请选择标签")
            return
        }
        if self.textView.text?.count == 0 {
            self.view.makeToast("请填写自我介绍")
            return
        }
        if self.textField.text?.count == 0 {
            self.view.makeToast("请输入手机号")
            return
        }
        
       
        
        var tagsString:String = ""
        var idsString:String = ""
        
        for (i,cooper) in items.enumerated() {
            if i == 0 {
                tagsString = "\(cooper.name)"
                idsString = "\(cooper.id)"
            }else{
                tagsString = "\(tagsString),\(cooper.name)"
                idsString = "\(idsString),\(cooper.id)"
            }
        }
        let param = [
            "tagNames": "\(tagsString)",
            "tagIds": "\(idsString)",
            "contactPhone": "\(self.textField.text!)",
            "content": "\(self.textView.text!)",
            "phoneNo":kUserPhone
                ] as [String:AnyObject]
        submitRequest(parameters:param )
    }
}

// 网络加载
extension SScooperateViewController {
    
    func submitRequest(parameters: [String:AnyObject]?) {

        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.addCooperation_URL, parameters: parameters) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    self.navigationController?.popViewController(animated: true)
                }else{
                    self.view.makeToast(retMsg)
                }
                
            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
    }
    
    func getCoopTag(){
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getCoopTag_URL, parameters: nil) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let data = json["data"]["listTags"].arrayValue
                var cooperList = [SSCooper]()
                data.forEach{
                    (num:JSON) in
                    let obj = SSCooper()
                    obj.id = num["id"].stringValue
                    obj.name = num["name"].stringValue
                    cooperList.append(obj)
                }
                self.cooperList = cooperList
                self.setuis()
            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
        
    }
}

///user/getCoopTag
//获取合作标签
    extension SScooperateViewController : UITextViewDelegate {
        public func textViewDidChange(_ textView: UITextView) {
            if textView.text.count > limitCount {
                // 获得已输出字数与正输入字母数
                let selectRange = textView.markedTextRange

                // 获取高亮部分 － 如果有联想词则解包成功
                if let selectRange = selectRange {
                    let position =  textView.position(from: (selectRange.start), offset: 0)
                    if (position != nil) {
                        return
                    }
                }

                let textContent = textView.text ?? ""
                let textNum = textContent.count

                // 截取
                if textNum > limitCount && limitCount > 0 {
                        textView.text = string_prefix(index: limitCount, text: textContent)
                }
            }
                self.limitCountLabel.text =  "\(textView.text.count)/\(limitCount)"
        }

        public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
                self.placeholderLabel.isHidden = true
            return true
        }

        public func textViewDidEndEditing(_ textView: UITextView) {
            if textView.text.isEmpty {
                    self.placeholderLabel.isHidden = false
            } else {
                    self.placeholderLabel.isHidden = true
            }
        }

        public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            if textView.returnKeyType == .done {
                if text == "\n" {
                    textView.resignFirstResponder()
                }
                return true
            }
            return true
        }

        // 字符串的截取 从头截取到指定index
        private func string_prefix(index:Int,text:String) -> String {
            if text.count <= index {
                return text
            } else {
                let index = text.index(text.startIndex, offsetBy: index)
                let str = text.prefix(upTo: index)
                return String(str)
            }
        }
}
